package com.everflourish.yeah100.adapter;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.everflourish.yeah100.R;
import com.everflourish.yeah100.act.menu.FragmentQuestion;
import com.everflourish.yeah100.act.questionlib.QuestionBankDetailActivity;
import com.everflourish.yeah100.entity.constant.SubjectEnum;
import com.everflourish.yeah100.entity.question.QuestionTag;
import com.everflourish.yeah100.http.ImageRequest;
import com.everflourish.yeah100.ui.CircleImageView;
import com.everflourish.yeah100.ui.dialog.LoadDialog;
import com.everflourish.yeah100.utils.IntentUtil;
import com.everflourish.yeah100.utils.KeyBoardUtils;
import com.everflourish.yeah100.utils.LogUtil;
import com.everflourish.yeah100.utils.MyToast;
import com.everflourish.yeah100.utils.constant.Constant;
import com.everflourish.yeah100.utils.constant.ResultCode;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 作者：Created by liqisi on 2016/7/28.
 * 时间：2016/7/28
 */
public class QuestionBankAdapter extends RecyclerView.Adapter<QuestionBankAdapter.QuestionBankHolder> {

    private Context mContext;
    private LayoutInflater mLayoutInflater;
    private List<QuestionTag> mList;
    private FragmentQuestion mFragment;
    private LoadDialog mLoadDialog;
    private ImageRequest imageRequest;
    private RequestQueue mQueue;

    public QuestionBankAdapter(Context mContext, List<QuestionTag> mList, FragmentQuestion mFragment) {
        this.mContext = mContext;
        this.mList = mList;
        this.mFragment = mFragment;
        mLayoutInflater = LayoutInflater.from(mContext);
        mQueue = Volley.newRequestQueue(mContext);
        imageRequest = ImageRequest.getInstance(mQueue);
    }

    @Override
    public QuestionBankHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = mLayoutInflater.inflate(R.layout.item_question_bank, parent, false);
        QuestionBankHolder viewHolder = new QuestionBankHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(final QuestionBankHolder holder, final int position) {
        final QuestionTag questionTag = mList.get(position);
        holder.questionBankNameTv.setVisibility(View.VISIBLE);
        holder.questionBankNameEt.setVisibility(View.GONE);
        KeyBoardUtils.closeKeybord(holder.questionBankNameEt, mContext);
        holder.questionBankNameTv.setText(questionTag.getTagName());
        holder.questionBankNameEt.setText(questionTag.getTagName());
        int result = new Random().nextInt(7) + 1;  // 产生1-7随机数
        if (result == 1) {
            holder.operationLl.setBackgroundColor(SubjectEnum.CHINESE.color);
        } else if (result == 2) {
            holder.operationLl.setBackgroundColor(SubjectEnum.MATH.color);
        } else if (result == 3) {
            holder.operationLl.setBackgroundColor(SubjectEnum.ENGLISH.color);
        } else if (result == 4) {
            holder.operationLl.setBackgroundColor(SubjectEnum.PHYSICS.color);
        } else if (result == 5) {
            holder.operationLl.setBackgroundColor(SubjectEnum.POLITICS.color);
        } else if (result == 6) {
            holder.operationLl.setBackgroundColor(SubjectEnum.OTHER.color);
        } else if (result == 7) {
            holder.operationLl.setBackgroundColor(SubjectEnum.CHEMISTRY.color);
        }
        imageRequest.get(holder.questionFirstIv, questionTag.getImageUrl());
        holder.mItemCv.setOnClickListener(new MyOnclickListener(holder, position));
        holder.deletTv.setOnClickListener(new MyOnclickListener(holder, position));
        holder.questionBankNameTv.setOnClickListener(new MyOnclickListener(holder, position));
        holder.questionBankNameEt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    /*隐藏软键盘*/
                    InputMethodManager imm = (InputMethodManager) v
                            .getContext().getSystemService(
                                    Context.INPUT_METHOD_SERVICE);
                    if (imm.isActive()) {
                        imm.hideSoftInputFromWindow(
                                v.getApplicationWindowToken(), 0);
                    }
                    updateQuestionLibTagRequest(questionTag.getTagId(),
                            holder.questionBankNameEt.getText().toString(), position);
                    return true;
                }
                return false;
            }
        });
    }

    @Override
    public int getItemCount() {
        return mList.size();
    }

    public class QuestionBankHolder extends RecyclerView.ViewHolder {

        private ImageView questionFirstIv;
        private LinearLayout operationLl;
        private CircleImageView headIv;
        private TextView questionBankNameTv;
        private EditText questionBankNameEt;
        private TextView deletTv;
        private RelativeLayout mItemRl;
        private CardView mItemCv;

        public QuestionBankHolder(View itemView) {
            super(itemView);
            questionFirstIv = (ImageView) itemView.findViewById(R.id.question_bank_first_image);
            operationLl = (LinearLayout) itemView.findViewById(R.id.question_bank_operation);
            headIv = (CircleImageView) itemView.findViewById(R.id.question_bank_head);
            questionBankNameTv = (TextView) itemView.findViewById(R.id.question_bank_name);
            questionBankNameEt = (EditText) itemView.findViewById(R.id.question_bank_name_et);
            deletTv = (TextView) itemView.findViewById(R.id.question_bank_delete);
            mItemRl = (RelativeLayout) itemView.findViewById(R.id.question_bank_item_rl);
            mItemCv = (CardView) itemView.findViewById(R.id.question_bank_item_cv);
        }
    }

    class MyOnclickListener implements View.OnClickListener {

        private QuestionBankHolder viewHolder;
        private int position;

        public MyOnclickListener(QuestionBankHolder viewHolder, int position) {
            this.viewHolder = viewHolder;
            this.position = position;
        }

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.question_bank_item_cv:
                    Intent questionIntent = new Intent(mContext,
                            QuestionBankDetailActivity.class);
                    questionIntent.putExtra(IntentUtil.QUESTION_TAG_ID, mList.get(position).getTagId());
                    questionIntent.putExtra(IntentUtil.QUESTION, mList.get(position));
                    mFragment.getActivity().startActivityForResult(questionIntent, 0x180);
                    break;
                case R.id.question_bank_delete:
                    AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                    builder.setMessage("确定要删除该标签吗？");
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            List<String> tagIds = new ArrayList<String>();
                            tagIds.add(mList.get(position).getTagId());
                            deleteQuestionTagRequest(tagIds, position);
                        }
                    });
                    builder.setNegativeButton("否", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    builder.show();
                    break;
                case R.id.question_bank_name:
                    viewHolder.questionBankNameTv.setVisibility(View.GONE);
                    viewHolder.questionBankNameEt.setVisibility(View.VISIBLE);
                    KeyBoardUtils.openKeybord(viewHolder.questionBankNameEt, mContext);
                    viewHolder.questionBankNameEt.requestFocus();
                    viewHolder.questionBankNameEt.requestFocusFromTouch();
                    viewHolder.questionBankNameEt.setSelection(viewHolder.questionBankNameEt.getText().toString().length());
                    break;
            }
        }
    }

    /**
     * 删除题库请求
     *
     * @param tagIds
     */
    private void deleteQuestionTagRequest(List<String> tagIds, final int position) {
        mLoadDialog = LoadDialog.show(mContext, null, "删除中...", mQueue);
        JsonObjectRequest request = mFragment.mRequest.deleteQuestionTagRequest(tagIds,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        deleteQuestionTagListener(response, position);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        mFragment.mRequest.disposeError(mContext, mLoadDialog, error, "删除题库失败");
                    }
                });
        mQueue.add(request);
    }

    /**
     * 老师修改标签名请求
     *
     * @param tagId
     * @param tagName
     */
    private void updateQuestionLibTagRequest(String tagId, final String tagName, final int position) {
        mLoadDialog = LoadDialog.show(mContext, null, "正在修改...");
        JsonObjectRequest request = mFragment.mRequest.updateQuestionLibTagRequest(tagId, tagName,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        updateQuestionLibTagListener(response, tagName, position);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        mFragment.mRequest.disposeError(mContext, mLoadDialog, error, "修改标签名失败");
                    }
                });
        mQueue.add(request);
    }

    /**
     * 老师取消收藏题目监听
     *
     * @param response
     */
    private void deleteQuestionTagListener(JSONObject response, int position) {
        try {
            String resultCode = response.getString(Constant.RESULT_CODE);
            if (resultCode.equals(ResultCode.result_ok.resultCode)) {
                mList.remove(position);
                notifyDataSetChanged();
                MyToast.showShort(mContext, "删除题库成功");
            } else if (resultCode.equals(ResultCode.result_000001E.resultCode)) {
                MyToast.showShort(mContext, R.string.questionlib_09201_000001E);
            } else if (resultCode.equals(ResultCode.result_300026E.resultCode)) {
                MyToast.showShort(mContext, R.string.questionlib_09202_300026E);
            } else if (resultCode.equals(ResultCode.result_system_exception_999999E)) {
                MyToast.showShort(mContext, R.string.questionlib_092099_999999E);
            } else {
                MyToast.showShort(mContext, "删除题库失败");
            }
        } catch (Exception e) {
            LogUtil.e("Json异常", e);
            MyToast.showShort(mContext, "删除题库失败");
        } finally {
            LoadDialog.dismiss(mLoadDialog);
        }
    }

    /**
     * 老师取消收藏题目监听
     *
     * @param response
     */
    private void updateQuestionLibTagListener(JSONObject response, String tagName, int position) {
        try {
            String resultCode = response.getString(Constant.RESULT_CODE);
            if (resultCode.equals(ResultCode.result_ok.resultCode)) {
                mList.get(position).setTagName(tagName);
                notifyDataSetChanged();
                MyToast.showShort(mContext, "修改标签名成功");
            } else if (resultCode.equals(ResultCode.result_000001E.resultCode)) {
                MyToast.showShort(mContext, R.string.questionlib_09211_000001E);
            } else if (resultCode.equals(ResultCode.result_300028E.resultCode)) {
                MyToast.showShort(mContext, R.string.questionlib_09212_300029E);
            } else if (resultCode.equals(ResultCode.result_system_exception_999999E)) {
                MyToast.showShort(mContext, R.string.questionlib_092199_999999E);
            } else {
                MyToast.showShort(mContext, "修改标签名失败");
            }
        } catch (Exception e) {
            LogUtil.e("Json异常", e);
            MyToast.showShort(mContext, "修改标签名失败");
        } finally {
            LoadDialog.dismiss(mLoadDialog);
        }
    }

}